package com.gmall.order.service;

import com.alibaba.fastjson.JSON;
import com.gmall.model.order.OrderInfo;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;

@Service
public class WareHttpClient {

    public boolean checkStock(Long skuId,Integer num) throws IOException {
        //http://localhost:9001/hasStock?skuId=19&num=1000000

        OkHttpClient okHttpClient = new OkHttpClient();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:9001/hasStock?skuId=")
                .append(URLEncoder.encode(skuId.toString(),"UTF-8"))
                .append("&num=")
                .append(URLEncoder.encode(num.toString(),"UTF-8"));
        
        Request request = new Request.Builder()
                .get()
                .url(stringBuilder.toString())
                .build();

        Response response = okHttpClient.newCall(request).execute();
        ResponseBody body = response.body();
        String result = body.string();
        return result.equals("1");
    }

    public boolean lockStockSku(OrderInfo orderInfo) throws IOException {
        //http://localhost:9001/lockWareSku
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                JSON.toJSONString(orderInfo)
        );
        Request request = new Request.Builder()
                .url("http://localhost:9001/lockWareSku")
                .post(requestBody)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        String body = response.body().string();
        return body.equals("1");
    }
}
